<template>
  <div class="bg-white shadow-md p-4">
    <Navigation :homeRoute="homeRoute" :currentPage="currentPage" />
  </div>
  <div class="treatment-apply-management">
    <!-- 顶部操作区 -->
    <div class="operation-header">
      <el-button 
        type="primary" 
        size="large"
        class="operate-btn"
        @click="openAddDialog"
      >
        新增诊疗申请
      </el-button>
    </div>

    <!-- 数据表格区 -->
    <div class="data-table-wrapper">
      <el-table 
        :data="treatmentApplies"
        height="calc(100vh - 220px)"
        style="width: 100%"
        class="enhanced-table"
      >
        <el-table-column 
          prop="applyId" 
          label="申请ID" 
          width="150"
          align="center"
        />
        <el-table-column 
          label="患者信息" 
          width="250"
          align="center"
        >
          <template #default="{ row }">
            <div>
              <p class="text-sm font-medium">{{ row.patient.real_name || '未知患者' }}</p>
              <p class="text-xs text-gray-500">ID: {{ row.patientId || '未知' }}</p>
              <p class="text-xs text-gray-500">科室: {{ row.patient.department.dept_name || '未知科室' }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column 
          label="医生信息" 
          width="250"
          align="center"
        >
          <template #default="{ row }">
            <div>
              <p class="text-sm font-medium">{{ row.doctor.real_name || '未知医生' }}</p>
              <p class="text-xs text-gray-500">ID: {{ row.doctorId || '未知' }}</p>
              <p class="text-xs text-gray-500">科室: {{ row.doctor.department.dept_name || '未知科室' }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column 
          prop="medicalItem.item_name" 
          label="诊疗项目" 
          width="200"
          align="center"
        />
        <el-table-column 
          prop="medicalItem.fee" 
          label="费用" 
          width="120"
          align="right"
        >
          <template #default="{ row }">
            <span class="text-sm text-gray-600">￥{{ row.medicalItem.fee || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column 
          prop="applyTime" 
          label="申请时间" 
          width="220"
          align="center"
        >
          <template #default="{ row }">
            <span class="time-display">
              {{ formatDate(row.applyTime) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column 
          prop="status" 
          label="状态" 
          width="120"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column 
          label="操作" 
          fixed="right" 
          width="120"
          align="center"
        >
          <template #default="{ row }">
            <el-button 
              type="primary" 
              link
              size="small"
              @click="viewDetails(row)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增诊疗申请"
      width="50%"
      class="data-form-dialog"
    >
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="120px"
        label-position="right"
      >
        <el-form-item label="患者ID：" prop="patientId">
          <el-input
            v-model.number="form.patientId"
            placeholder="请输入患者ID"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="医生ID：" prop="doctorId">
          <el-input
            v-model.number="form.doctorId"
            placeholder="请输入医生ID"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="项目ID：" prop="itemId">
          <el-input
            v-model.number="form.itemId"
            placeholder="请输入项目ID"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="申请时间：" prop="applyTime">
          <el-input
            v-model="form.applyTimeStr"
            placeholder="请输入时间（格式：yyyy-MM-dd HH:mm:ss）"
            @blur="handleTimeInput"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleSubmit"
          >
            立即创建
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="诊疗申请详情"
      width="60%"
      class="detail-dialog"
    >
      <el-card class="detail-card">
        <div class="detail-item">
          <span class="detail-label">申请ID：</span>
          <span class="detail-value">{{ detailData.applyId }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">患者姓名：</span>
          <span class="detail-value">{{ detailData.patient.real_name || '未知' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">患者ID：</span>
          <span class="detail-value">{{ detailData.patientId || '未知' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">医生姓名：</span>
          <span class="detail-value">{{ detailData.doctor.real_name || '未知' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">医生ID：</span>
          <span class="detail-value">{{ detailData.doctorId || '未知' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">诊疗项目：</span>
          <span class="detail-value">{{ detailData.medicalItem.item_name || '未知项目' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">项目类型：</span>
          <span class="detail-value">{{ detailData.medicalItem.item_type || '未知类型' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">申请时间：</span>
          <span class="detail-value">{{ formatDate(detailData.applyTime) }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">状态：</span>
          <span class="detail-value">
            <el-tag :type="getStatusType(detailData.status)">{{ getStatusText(detailData.status) }}</el-tag>
          </span>
        </div>
        <div class="detail-item" v-if="detailData.medicalItem.description">
          <span class="detail-label">项目描述：</span>
          <span class="detail-value">{{ detailData.medicalItem.description }}</span>
        </div>
      </el-card>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, defineExpose } from 'vue';
import { FormInstance, ElMessage } from 'element-plus';
import axios from 'axios';
import Navigation from '@/components/Navigation.vue';
// 状态管理
const treatmentApplies = ref([]);
const dialogVisible = ref(false);
const detailVisible = ref(false);
const detailData = ref({});
const formRef = ref<FormInstance>();
const currentPage = '登记信息';
// 表单数据
const form = reactive({
  patientId: 0,
  doctorId: 0,
  itemId: 0,
  applyTime: Date.now(), // 时间戳
  applyTimeStr: new Date().toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-'), // 默认当前时间字符串
  status: 0 // 待处理状态
});

// 表单验证规则
const formRules = reactive({
  patientId: [
    { required: true, message: '请输入患者ID', trigger: 'blur' },
    { type: 'number', message: '请输入有效数字', trigger: 'blur' }
  ],
  doctorId: [
    { required: true, message: '请输入医生ID', trigger: 'blur' },
    { type: 'number', message: '请输入有效数字', trigger: 'blur' }
  ],
  itemId: [
    { required: true, message: '请输入项目ID', trigger: 'blur' },
    { type: 'number', message: '请输入有效数字', trigger: 'blur' }
  ],
  applyTime: [
    { required: true, message: '请输入申请时间', trigger: 'blur' }
  ]
});

// 日期格式化函数
const formatDate = (timestamp: number) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 时间输入处理函数
const handleTimeInput = (e: any) => {
  const inputValue = e.target.value.trim();
  const date = new Date(inputValue.replace(/-/g, '/')); // 兼容日期格式
  if (isNaN(date.getTime())) {
    form.applyTime = Date.now();
    form.applyTimeStr = formatDate(form.applyTime);
    return ElMessage.error('时间格式不正确，请使用 yyyy-MM-dd HH:mm:ss 格式');
  }
  form.applyTime = date.getTime();
  form.applyTimeStr = inputValue;
};

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0: return '待处理';
    case 1: return '已处理';
    case 2: return '已取消';
    default: return '未知状态';
  }
};

// 获取状态标签类型
const getStatusType = (status: number) => {
  switch (status) {
    case 0: return 'warning';
    case 1: return 'success';
    case 2: return 'info';
    default: return 'default';
  }
};

// 加载数据
const fetchData = async () => {
  try {
    const response = await axios.get('/treatmentapply/findAll');
    if (Array.isArray(response.data)) {
      treatmentApplies.value = response.data;
    } else {
      throw new Error("数据格式错误");
    }
  } catch (error) {
    ElMessage.error('数据加载失败：' + error.message);
  }
};

// 打开新增对话框
const openAddDialog = () => {
  resetForm();
  dialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  form.patientId = 0;
  form.doctorId = 0;
  form.itemId = 0;
  form.applyTime = Date.now();
  form.applyTimeStr = new Date().toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-');
  form.status = 0;
};

// 查看详情
const viewDetails = (row: any) => {
  detailData.value = row;
  detailVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    const requestData = {
      patientId: form.patientId,
      doctorId: form.doctorId,
      itemId: form.itemId,
      applyTime: form.applyTime,
      status: form.status
    };

    const response = await axios.post(
      'http://localhost:8080/DazuoyePromax/treatmentapply/add', 
      requestData,
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    );

    if (response.data === '添加成功') {
      ElMessage.success('新增成功');
      dialogVisible.value = false;
      fetchData();
    } else {
      ElMessage.error(response.data || '操作失败，请重试');
    }
  } catch (error: any) {
    console.error('操作失败:', error);
    if (error.response) {
      ElMessage.error(`操作失败: ${error.response.status} ${error.response.data}`);
    } else {
      ElMessage.error('网络错误，请检查连接');
    }
  }
};

// 初始化数据
onMounted(fetchData);

// 暴露方法给组件实例
defineExpose({
  openAddDialog
});
</script>

<style scoped>
.treatment-apply-management {
  height: 100vh;
  padding: 20px;
  background: #f6f8fa;
  box-sizing: border-box;
}

.operation-header {
  padding: 15px 20px;
  background: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
}

.operate-btn {
  padding: 0 28px;
  height: 42px;
  font-size: 15px;
}

.data-table-wrapper {
  background: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
}

.enhanced-table {
  font-size: 15px;
}

.enhanced-table :deep(.el-table__header th) {
  background-color: #f8fafc;
  color: #333;
  font-weight: bold;
  height: 60px;
}

.enhanced-table :deep(.el-table__row) {
  height: 56px;
}

.enhanced-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.content-preview {
  line-height: 1.6;
  max-height: 120px;
  overflow: auto;
  padding-right: 10px;
}

.time-display {
  color: #666;
}

.action-btns {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.data-form-dialog :deep(.el-dialog__body) {
  padding: 20px 25px;
}

.data-form-dialog :deep(.el-form-item__label) {
  font-weight: 500;
  color: #555;
}

.data-form-dialog :deep(.el-input__inner),
.data-form-dialog :deep(.el-textarea__inner) {
  font-size: 15px;
}

.dialog-footer {
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.detail-item {
  display: flex;
  align-items: center;
  margin: 15px 0;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.detail-label {
  min-width: 100px;
  text-align: right;
  margin-right: 20px;
  color: #666;
  font-weight: 500;
}

.detail-value {
  flex: 1;
  color: #333;
  line-height: 1.6;
}
</style>